package com.bawei.lib_common.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.SweepGradient
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.core.app.NotificationCompat.Style
import androidx.core.content.ContextCompat
import com.bawei.lib_common.R
import kotlin.math.min

class CircleCountDownView @JvmOverloads constructor(context:Context,attrs:AttributeSet?=null,defaultStyle:Int=0):View(context,attrs,defaultStyle) {

    private var progressColor = Color.BLUE
    private var progressBackgroundColor = Color.LTGRAY
    private var progressWidth = 20F
    private var textColor = Color.BLACK
    private var textSize = 40F
    private var countDownTime = 5
    private var textY = 0f

    private var centerX = 0f
    private var centerY = 0f
    private var radius = 0f

    private var sweepAngle = 0f
    private var currentAngle = 0f

    private var remainingTime = countDownTime //剩余时间
    private var animator: ValueAnimator? = null
    private var countDownListener: CountDownListener? = null


    //背景画笔
    private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        color = progressBackgroundColor
        strokeWidth = progressWidth
        strokeCap = Paint.Cap.ROUND
    }

    //进度条的画笔
    private val progressPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        color = progressColor
        strokeWidth = progressWidth
        strokeCap = Paint.Cap.ROUND

    }

    //进度条底色画笔
    private val gradientPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeWidth = progressWidth
        strokeCap = Paint.Cap.ROUND
        shader = SweepGradient(centerX, centerY, intArrayOf(Color.RED, Color.YELLOW, Color.GREEN), null)

    }

    //文本画笔
    private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = textColor
        textSize = textSize
        textAlign = Paint.Align.CENTER
        typeface = Typeface.DEFAULT_BOLD
    }

    init {
        attrs?.run {
            //获取自定义属性值
            val typeArray = context.obtainStyledAttributes(this, R.styleable.CircleCountDownView)
            progressColor = typeArray.getColor(R.styleable.CircleCountDownView_progressColor, ContextCompat.getColor(context, R.color.blueviolet))
            progressBackgroundColor = typeArray.getColor(R.styleable.CircleCountDownView_progressBackgroundColor, Color.LTGRAY)
            progressWidth = typeArray.getDimension(R.styleable.CircleCountDownView_progressWidth, 20F)
            textColor = typeArray.getColor(R.styleable.CircleCountDownView_textColor, Color.BLACK)
            textSize = typeArray.getDimension(R.styleable.CircleCountDownView_textSize, 40F)
            countDownTime = typeArray.getInteger(R.styleable.CircleCountDownView_countDownTime, 5)
            //释放资源, 避免内存泄漏
            typeArray.recycle()
        }

        //重置画笔属性
        backgroundPaint.strokeWidth = progressWidth
        progressPaint.strokeWidth = progressWidth
        gradientPaint.strokeWidth = progressWidth
        textPaint.color = textColor
        textPaint.textSize = textSize

        //剩余时间
        remainingTime = countDownTime
    }

    fun setCountDownListener(l: CountDownListener){
        countDownListener = l
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        //中心点坐标
        centerX = w / 2f
        centerY = h / 2f
        //获取半径
        radius = (min(w, h) - progressWidth) / 2f
    }

    /**
     * 注意事项：
     * 1.不要在onDraw方法中创建临时变量或对象，避免内存抖动
     * 2.不要做复杂计算
     */
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        //绘制圆形背景
        canvas.drawCircle(centerX, centerY, radius, backgroundPaint)

        //绘制进度条
        sweepAngle = 360 * (currentAngle / 100f)
        canvas.drawArc(centerX - radius, centerY - radius, centerX + radius, centerY + radius, -90f, sweepAngle, false, gradientPaint)

        //绘制文本
        textY = centerY - (textPaint.descent() + textPaint.ascent()) / 2f
        canvas.drawText("${remainingTime}s跳过", centerX, textY, textPaint)
    }


    /**
     * 开启倒计时
     */
    fun startCountDown(){
        animator = ValueAnimator.ofFloat(0f, 100f).apply {
            duration = (countDownTime * 1000).toLong()
            interpolator = LinearInterpolator() //匀速执行动画
            //添加监听事件
            addUpdateListener {
                currentAngle = it.animatedValue as Float
                remainingTime = countDownTime - ((currentAngle / 100f) * countDownTime).toInt()
                //重新绘制UI
                invalidate()
                //倒计时结束
                if (remainingTime == 0){
                    countDownListener?.countDownFinished()
                }
            }
        }

        //执行动画
        animator?.start()
    }

    /**
     * 开关倒计时
     */
    fun stopCountDown(){
        animator?.cancel()
        animator = null
    }

    /**
     * 当组件从窗口解绑时回调
     */
    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stopCountDown()
    }

    /**
     * 定义接口
     */
    interface CountDownListener {
        fun countDownFinished()
    }




}